package xp2p.trashes;

import java.io.IOException;
import java.util.Dictionary;
import java.util.HashMap;

import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.id.IDFactory;
import net.jxta.peer.PeerID;
import net.jxta.peergroup.PeerGroup;
import net.jxta.pipe.PipeID;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.PeerAdvertisement;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.socket.JxtaSocket;
import net.jxta.socket.JxtaSocketAddress;

public class ChannelProvider
{
	private int connectTimeout = 120000; // TODO get connect timeout from configuration
	private PeerGroup pg;
	private HashMap<PeerID, JxtaSocketAddress> _cache = new HashMap<PeerID, JxtaSocketAddress>();
	
	public JxtaSocket getChannel(PeerID id) throws IOException
	{		
		JxtaSocketAddress addr;
		if (_cache.containsKey(id))
		{
			addr =_cache.get(id);
		}
		addr = GetAdvertisement(id);
		_cache.put(id, addr);
		JxtaSocket result = new JxtaSocket(addr,connectTimeout);
		return result;
	}
	
	private JxtaSocketAddress GetAdvertisement(PeerID id)
	{
		PipeAdvertisement adv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());
		PeerAdvertisement peer = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(PeerAdvertisement.getAdvertisementType());
		peer.setPeerID(id);
		PipeID pipeId = IDFactory.newPipeID(pg.getPeerGroupID(), (id.toString()+"unicast").getBytes());
		adv.setPipeID(pipeId);
		adv.setName("messages");		
		adv.setType(PipeService.UnicastType);
		adv.setDescription("pipe for xp2p messages");
		return new JxtaSocketAddress(pg,adv, peer);				
	}
}
